package com.steven.ourcontest.chat.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.steven.ourcontest.base.BaseViewModel
import com.steven.ourcontest.chat.api.ChatApi
import com.steven.ourcontest.chat.bean.FriendList
import com.steven.ourcontest.utils.plusAssign

class FriendViewModel : BaseViewModel() {
    private val _queryFriendsResponse = MutableLiveData<FriendList>()
    val queryFriendsResponse: LiveData<FriendList>
        get() = _queryFriendsResponse

    private val _updateFriendShip = MutableLiveData<Long>()
    val updateFriendShip: LiveData<Long>
        get() = _updateFriendShip

    private var isQueryingFriends = false
    fun queryFriends() {
        if (isQueryingFriends)
            return
        isQueryingFriends = true
        disposed += ChatApi.instance.queryFriends()
            .subscribe({
                isQueryingFriends = false
                _queryFriendsResponse.value = it
            }, {
                isQueryingFriends = false
                it.printStackTrace()
            })
    }

    fun updateApplicantReadStatus() {
        disposed += ChatApi.instance.updateApplicantReadStatus()
            .subscribe({
            }, {
                it.printStackTrace()
            })
    }

    fun updateFriendShip(applicantUser: Long, agree: Boolean) {
        disposed += ChatApi.instance.updateApplication(applicantUser, agree)
            .flatMap {
                return@flatMap ChatApi.instance.updateApplicantReadStatus()
            }.flatMap {
                return@flatMap ChatApi.instance.sendMessageTo(applicantUser, "Hello，我们已经成为好友了！")
            }.subscribe({
                _updateFriendShip.value = applicantUser
            }, {
                it.printStackTrace()
            })
    }

    fun updateMessageStatus(sendUser:Long,success:(()->Unit)) {
        disposed += ChatApi.instance.updateMessageStatus(sendUser)
            .subscribe({
                success.invoke()
            }, {
                it.printStackTrace()
            })
    }
}